package com.swz.dcrm.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.Observer;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.swz.dcrm.R;
import com.swz.dcrm.digger.AppModule;
import com.swz.dcrm.digger.DaggerAppComponent;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.Token;
import com.swz.dcrm.ui.base.BaseActivity;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.util.SPUtils;
import com.swz.dcrm.util.SingleClick;
import com.swz.dcrm.util.Tool;
import com.xh.baselibrary.model.RequestErrBean;
import com.xh.baselibrary.widget.ClickImageView;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import qiu.niorgai.StatusBarCompat;

public class LoginActivity extends BaseActivity implements Validator.ValidationListener {

    @NotEmpty(messageResId = R.string.not_be_null_account)
    @BindView(R.id.et_account)
    EditText etAccount;
    @NotEmpty(messageResId = R.string.not_be_null_pwd)
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_login)
    ImageView ivLogin;
    private Validator validator;
    @Inject
    MainViewModel mainViewModel;
    ValueAnimator  valueAnimator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        DaggerAppComponent.builder().appModule(new AppModule(this))
                .build().inject(this);
        StatusBarCompat.translucentStatusBar(this, true);
        validator=new Validator(this);
        validator.setValidationListener(this);
        String account=SPUtils.getAccount(this);
        String pwd=SPUtils.getPwd(this);
        if(!TextUtils.isEmpty(account)){
            etAccount.setText(account);
            etPwd.setText(pwd);
            etPwd.requestFocus();
            etPwd.setSelection(etPwd.getText().toString().length());
        }
        mainViewModel.getLoginResult().observe(this, tokenBaseResponse -> {
            ivLogin.setClickable(true);
            valueAnimator.end();
            if(tokenBaseResponse.isSuccess()){
                SPUtils.putAccount(this,etAccount.getText().toString());
                SPUtils.putPwd(this,etPwd.getText().toString());
                MyApplication myApplication= (MyApplication) getApplication();
                myApplication.setToken(tokenBaseResponse.getData().getToken());
                Intent intent=new Intent(this, MainActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }else {
                showToast(tokenBaseResponse.getMsg());
            }
        });
        mainViewModel.getErrorLiveData().observe(this, requestErrBean -> {
            if(ivLogin!=null){
                ivLogin.setClickable(true);
            }
            if(valueAnimator!=null){
                valueAnimator.end();
                ivLogin.setRotation(0);
            }
            showToast(requestErrBean.getMessage());
        });



    }

    @OnClick({R.id.iv_login,R.id.tv_forget_pwd})
    @SingleClick
    public void click(View view){
        switch (view.getId()){
            case R.id.iv_login:
                validator.validate();
                break;
            case R.id.tv_forget_pwd:
                Intent intent=new Intent(this, PwdResetActivity.class);
                startActivity(intent);
                break;

        }
    }

    @Override
    public void onValidationSucceeded() {
        String account=etAccount.getText().toString().trim();
        String pwd=etPwd.getText().toString().trim();
        valueAnimator = ObjectAnimator.ofFloat(0,360f);
        valueAnimator.addUpdateListener(animation -> ivLogin.setRotation((Float) animation.getAnimatedValue()));
        valueAnimator.setDuration(2000);
        valueAnimator.setRepeatCount(Animation.INFINITE);//设定无限循环
        valueAnimator.setRepeatMode(ObjectAnimator.RESTART);// 循环模式
        valueAnimator.setInterpolator(new LinearInterpolator());// 匀速
        valueAnimator.start();
        ivLogin.setClickable(false);
        mainViewModel.login(account, Tool.md5(pwd));
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);
            // Display error messages ;)
            if (view instanceof EditText) {
                ((EditText) view).setError(message);
                view.requestFocus();
            }
        }
    }
}
